package com.netease.nie.facade;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netease.nie.base.utils.CopyUtils;
import com.netease.nie.base.utils.DateUtils;
import com.netease.nie.constants.OrdersTraceConstants;
import com.netease.nie.dto.AddressDto;
import com.netease.nie.dto.ConfirmedOrdersAddressDto;
import com.netease.nie.model.Orders;
import com.netease.nie.model.OrdersAddress;
import com.netease.nie.model.OrdersTrace;
import com.netease.nie.service.AddressService;
import com.netease.nie.service.ConfirmedOrdersAddressService;
import com.netease.nie.service.OrderService;

@Service
public class ConfirmedOrdersAddressFacadeImpl implements
		ConfirmedOrdersAddressFacade {

	@Autowired
	private ConfirmedOrdersAddressService confirmedOrdersAddressService;

	@Autowired
	private AddressService addressService;
	
	@Autowired
	private OrderService orderService;

	public int confirmed(long userId, ConfirmedOrdersAddressDto confirmedOrdersAddressDto) {
		long addressId = confirmedOrdersAddressDto.getAddressId();
		long orderId = confirmedOrdersAddressDto.getOrderId();
		AddressDto addressDto = addressService.listAddressById(addressId, userId);
		OrdersAddress ordersAddress = generateOrdersAddress(orderId, addressDto);
		Orders orders = orderService.getOrderByOrderIdAndUserId(orderId, userId);
		OrdersTrace ordersTrace = generateOrdersTrace(orders);
		if (ordersAddress != null && ordersAddress != null) {
			try {
				return confirmedOrdersAddressService.confirmed(ordersAddress, ordersTrace);
			} catch (Exception e) {
				
			}
		}
		return 0;
	}
	
	private OrdersAddress generateOrdersAddress(long orderId, AddressDto addressDto) {
		if (addressDto != null) {
			OrdersAddress ordersAddress = new OrdersAddress();
			CopyUtils.copy(ordersAddress, addressDto);
			ordersAddress.setOrderId(orderId);
			return ordersAddress;
		}
		return null;
	}
	
	private OrdersTrace generateOrdersTrace(Orders orders) {
		if (orders != null) {
			OrdersTrace ordersTrace = new OrdersTrace();
			CopyUtils.copy(ordersTrace, orders);
			ordersTrace.setOrderId(orders.getId());
			ordersTrace.setStatus(OrdersTraceConstants.CONFIRM_ADDRESS.getCode());
			ordersTrace.setCreateTime(DateUtils.currentTimeInMills());
			return ordersTrace;
		}
		return null;
	}
}
